package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * author：sch
 * createTime：2025/10/17 17:21
 * description： 定义日志记录切面
 *
 * 增删改操作都记录到日志表里
 */
@Aspect
@Component
@Slf4j
public class LogRecordAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    //定义切点
    @Pointcut("@annotation(com.qk.management.aop.anno.LoginAnno)")
    public void pt() {}
    //定义通知
    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp){
        //定义目标方法的返回值
        Object returnValue = null;
        try {
            //前置逻辑
            long startTime = System.currentTimeMillis();
            //执行目标方法-------------------------
            returnValue = pjp.proceed();
            //-----------------------------------
            //后置逻辑
            long endTime = System.currentTimeMillis();
            //构造一个OperateLog对象
            OperateLog operateLog = OperateLog.builder()
                    .operateUserId(CurrentUserContextHolders.get())//操作用户ID
                    .operateTime(LocalDateTime.now())//操作时间
                    .className(pjp.getTarget().getClass().getName())//类名称
                    .methodName(pjp.getSignature().getName())//方法名称
                    .methodParams(JSONUtil.toJsonStr(pjp.getArgs()))//方法参数
                    .returnValue(JSONUtil.toJsonStr(returnValue))//返回值
                    .costTime(endTime - startTime)//耗时
                    .build();
            //调用Mapper写入数据库
            try {
                operateLogMapper.insert(operateLog);
            }catch (Exception e){
                log.error("操作日志写入数据库记录失败:{}", e.getMessage());
            }
        } catch (Throwable e) {
            returnValue = Result.error("操作失败,加纳");
        }
        return returnValue;
    }
}